package jnpf.controller;

import jnpf.base.ActionResult;
import jnpf.model.ragFlow.talkAssistant.ChatCreateReq;
import jnpf.model.ragFlow.talkAssistant.ChatDeleteReq;
import jnpf.model.ragFlow.talkAssistant.ChatUpdateReq;
import org.springframework.core.io.Resource;

import io.swagger.annotations.ApiOperation;
import jnpf.model.ragFlow.chunk.*;
import jnpf.model.ragFlow.common.DocumentIdsReq;
import jnpf.model.ragFlow.common.IdReq;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.file.DocumentListRequest;
import jnpf.model.ragFlow.file.DocumentUpdateRequest;
import jnpf.model.ragFlow.know.CreateKnowReq;
import jnpf.model.ragFlow.know.DatasetListRequest;
import jnpf.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api/example/ragFlow")
public class RagFlowController {
    @Autowired
    private RagFlowKnowService knowService;

    @Autowired
    private RagFlowFileService fileService;

    @Autowired
    private RagTalkAssistantService talkAssistantService;

    @Autowired
    private RagChunksService chunksService;

    @Autowired
    private RagTalkMangeService talkMangeService;
    @Autowired
    private DifyKnowService difyKnowService;

    // 知识库相关接口
    @PostMapping("/know/createDataset")
    @ApiOperation(value = "创建空数据集")
    public RagFlowApiResult createDataset(@RequestBody CreateKnowReq createDataSetsReq) throws Exception {
        return knowService.createDataset(createDataSetsReq);
    }

    @PostMapping("/know/deleteDataset")
    @ApiOperation(value = "删除数据集")
    public RagFlowApiResult deleteDataset(@RequestBody IdReq idReq) throws Exception {
        return knowService.deleteDataset(idReq);
    }

    @PostMapping("/know/updateDataset/{datasetId}")
    @ApiOperation(value = "更新数据集")
    public RagFlowApiResult updateDataset(@RequestBody CreateKnowReq createDataSetsReq, @PathVariable String datasetId) throws Exception {
        return knowService.updateDataset(createDataSetsReq, datasetId);
    }

    @GetMapping("/know/getDatasetList")
    @ApiOperation(value = "获取数据集列表")
    public RagFlowApiResult getDatasetList(@RequestBody DatasetListRequest datasetListRequest) throws Exception {
        return knowService.getDatasetList(datasetListRequest);
    }

    // 文件相关接口
    @PostMapping("/file/upload/{datasetId}")
    @ApiOperation(value = "上传文件到指定数据集")
    public RagFlowApiResult uploadFiles(@PathVariable String datasetId, @RequestParam List<MultipartFile> files) throws Exception {
        return fileService.uploadFiles(datasetId, files);
    }

    @PostMapping("/file/update/{datasetId}/{documentId}")
    @ApiOperation(value = "更新文档")
    public RagFlowApiResult updateDocument(@PathVariable String datasetId, @PathVariable String documentId, @RequestBody DocumentUpdateRequest documentReq) throws Exception {
        return fileService.updateDocument(datasetId, documentId, documentReq);
    }

    @GetMapping("/file/download/{datasetId}/{documentId}/{extension}")
    public ResponseEntity<byte[]> downloadDocument(@PathVariable String datasetId, @PathVariable String documentId, @PathVariable String extension) throws Exception {
        byte[] fileBytes = fileService.downloadDocument(datasetId, documentId);
        String contentType = determineContentType(extension);

        // **关键修改：将 attachment 改为 inline**
        String contentDisposition = String.format("inline; filename=\"%s.%s\"", documentId, extension);

        return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)).header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition).body(fileBytes);
    }

    private String determineContentType(String documentId) {
        String extension = documentId.substring(documentId.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "txt":
                return "text/plain";
            case "md":
                return "text/markdown"; // 新增 Markdown 类型
            case "pdf":
                return "application/pdf";
            case "jpg":
                return "image/jpeg";
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "ppt":
            case "pptx":
                return "application/vnd.ms-powerpoint"; // PPT 格式
            case "xls":
            case "xlsx":
                return "application/vnd.ms-excel"; // Excel 格式
            case "doc":
            case "docx":
                return "application/msword"; // Word 格式
            default:
                return "application/octet-stream";
        }
    }

    @PostMapping("/file/list/{datasetId}")
    @ApiOperation(value = "获取文档列表")
    public Object listDocuments(@PathVariable String datasetId, @RequestBody DocumentListRequest request) throws Exception {
        RagFlowApiResult ragFlowApiResult = fileService.listDocuments(datasetId, request);
        if (ragFlowApiResult.getCode() == 0) {
            return ActionResult.success(ragFlowApiResult);
        } else {
            return ragFlowApiResult;
        }
    }

    @DeleteMapping("/file/delete/{datasetId}")
    @ApiOperation(value = "删除文档")
    public RagFlowApiResult deleteDocuments(@PathVariable String datasetId, @RequestBody IdReq idReq) throws Exception {
        return fileService.deleteDocuments(datasetId, idReq);
    }

    @PostMapping("/file/parse/{datasetId}")
    @ApiOperation(value = "解析文档")
    public RagFlowApiResult parseDocuments(@PathVariable String datasetId, @RequestBody DocumentIdsReq documentIds) throws Exception {
        return fileService.parseDocuments(datasetId, documentIds);
    }

    @PostMapping("/file/stopParse/{datasetId}")
    @ApiOperation(value = "停止解析文档")
    public RagFlowApiResult stopParsingDocuments(@PathVariable String datasetId, @RequestBody DocumentIdsReq documentIds) throws Exception {
        return fileService.stopParsingDocuments(datasetId, documentIds);
    }

    // 数据块相关接口
    @PostMapping("/chunks/add/{datasetId}/{documentId}")
    @ApiOperation(value = "添加数据块")
    public RagFlowApiResult addChunks(@PathVariable String datasetId, @PathVariable String documentId, @RequestBody AddChunksRequest request) throws Exception {
        return chunksService.addChunks(datasetId, documentId, request);
    }

    @GetMapping("/chunks/list/{datasetId}/{documentId}")
    @ApiOperation(value = "列出数据块")
    public RagFlowApiResult listChunks(@PathVariable String datasetId, @PathVariable String documentId, @RequestBody ListChunksRequest request) throws Exception {
        return chunksService.listChunks(datasetId, documentId, request);
    }

    @DeleteMapping("/chunks/delete/{datasetId}/{documentId}")
    @ApiOperation(value = "删除数据块")
    public RagFlowApiResult deleteChunks(@PathVariable String datasetId, @PathVariable String documentId, @RequestBody DeleteChunksRequest request) throws Exception {
        return chunksService.deleteChunks(datasetId, documentId, request);
    }

    @PutMapping("/chunks/update/{datasetId}/{documentId}/{chunkId}")
    @ApiOperation(value = "更新数据块")
    public RagFlowApiResult updateChunk(@PathVariable String datasetId, @PathVariable String documentId, @PathVariable String chunkId, @RequestBody UpdateChunkRequest request) throws Exception {
        return chunksService.updateChunk(datasetId, documentId, chunkId, request);
    }

    @GetMapping("/chunks/retrieve")
    @ApiOperation(value = "检索数据块")
    public RagFlowApiResult retrieveChunks(@RequestBody RetrieveChunksRequest request) throws Exception {
        return chunksService.retrieveChunks(request);
    }


    //TODO 这些接口暂时没做，看需求
//    // 聊天助手相关接口
    @PostMapping("/talkAssistant/create")
    @ApiOperation(value = "创建聊天助手")
    public RagFlowApiResult createChat(@RequestBody ChatCreateReq request) throws Exception {
        return talkAssistantService.createChat(request);
    }

    //
    @PutMapping("/talkAssistant/update/{chatId}")
    @ApiOperation(value = "更新聊天助手")
    public RagFlowApiResult updateChat(@PathVariable String chatId, @RequestBody ChatUpdateReq request) throws Exception {
        return talkAssistantService.updateChat(chatId, request);
    }

    @DeleteMapping("/talkAssistant/delete")
    @ApiOperation(value = "删除聊天助手")
    public RagFlowApiResult deleteChat(@RequestBody ChatDeleteReq request) throws Exception {
        return talkAssistantService.deleteChat(request);
    }


    @GetMapping("/talkAssistant/list")
    @ApiOperation(value = "获取聊天助手列表")
    public RagFlowApiResult listChats(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) String orderby, @RequestParam(required = false) Boolean desc, @RequestParam(required = false) String name, @RequestParam(required = false) String id) throws Exception {
        return talkAssistantService.listChats(page, pageSize, orderby, desc, name, id);
    }


    @GetMapping("/getObjImg/{knowId}/{fileId}")
    @ApiOperation(value = "获取实例图谱")
    public ActionResult listChats(@PathVariable("knowId") String knowId, @PathVariable("fileId") String fileId) throws Exception {
        return difyKnowService.getObjRelation(knowId, fileId);
    }


    @GetMapping("/getModelSelect")
    @ApiOperation(value = "获取模型可选列表")
    public ActionResult getModelSelectList() throws Exception {
        return difyKnowService.getModelSelectList();
    }

    @GetMapping("/getKnowSelect")
    @ApiOperation(value = "获取知识库可选列表")
    public ActionResult getKnowSelect() throws Exception {
        return difyKnowService.getKnowSelect();
    }




//
//    // 会话管理相关接口
//    @PostMapping("/talkMange/createSession/{chatId}")
//    @ApiOperation(value = "创建会话")
//    public RagFlowApiResult createSession(@PathVariable String chatId,
//                                        @RequestBody SessionCreateReq request) throws Exception {
//        return talkMangeService.createSession(chatId, request);
//    }
//
//    @PutMapping("/talkMange/updateSession/{chatId}/{sessionId}")
//    @ApiOperation(value = "更新会话")
//    public RagFlowApiResult updateSession(@PathVariable String chatId,
//                                       @PathVariable String sessionId,
//                                       @RequestBody SessionUpdateReq request) throws Exception {
//        return talkMangeService.updateSession(chatId, sessionId, request);
//    }
//
//    @DeleteMapping("/talkMange/deleteSessions/{chatId}")
//    @ApiOperation(value = "删除会话")
//    public RagFlowApiResult deleteSessions(@PathVariable String chatId,
//                                         @RequestBody SessionDeleteReq request) throws Exception {
//        return talkMangeService.deleteSessions(chatId, request);
//    }
//
//    @GetMapping("/talkMange/listSessions/{chatId}")
//    @ApiOperation(value = "获取会话列表")
//    public RagFlowApiResult listSessions(@PathVariable String chatId,
//                                       @RequestParam(required = false) Integer page,
//                                       @RequestParam(required = false) Integer pageSize,
//                                       @RequestParam(required = false) String orderby,
//                                       @RequestParam(required = false) Boolean desc,
//                                       @RequestParam(required = false) String name,
//                                       @RequestParam(required = false) String id) throws Exception {
//        return talkMangeService.listSessions(chatId, page, pageSize, orderby, desc, name, id);
//    }
}
